﻿namespace AddressBook.Business.Person
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
  using System.Text.RegularExpressions;

	using Csla;
	using Csla.Data;
	#endregion

	[Serializable]
	public class EmailAddress
	{
		#region "Factory Methods"

    private static string sRegexEmailPattern = "^.+?@.+?\\..+?\\z";

    public static bool IsValidPhone(string phoneNumber)
    {
      return Regex.IsMatch(phoneNumber, sRegexEmailPattern);
    }

		private EmailAddress()
		{ /*require use of factory methods*/ }

		#endregion

		#region "Data Access"

		public static Int32 AddEmailAddress(string emailAddress)
		{
			int emailAddressId;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.EmailAddress email = new AddressBook.Business.Model.EmailAddress();

				email.EmailAddress1 = emailAddress;
				email.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.EmailAddresses.InsertOnSubmit(email);
				ctx.DataContext.SubmitChanges();

				emailAddressId = email.Id;
			}

			return emailAddressId;
		}

		public static void UpdateEmailAddress(Int32 id, string emailAddress)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.EmailAddress email = ctx.DataContext.EmailAddresses.First(e => e.Id == id);

				email.EmailAddress1 = emailAddress;
				email.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.SubmitChanges();
			}
		}

		public static void RemoveEmailAddress(Int32 id)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.EmailAddress email = ctx.DataContext.EmailAddresses.First(e => e.Id == id);

				ctx.DataContext.EmailAddresses.DeleteOnSubmit(email);
				ctx.DataContext.SubmitChanges();
			}
		}

		#endregion
	}
}
